package n2_common_methods;

import lombok.extern.slf4j.Slf4j;

/**
 * Java里的运行：Runnable [有可能分到时间片]，[也有可能分不到] ，[也有可能陷入到操作系统的IO阻塞]
 */
@Slf4j(topic = "c.T10")
public class T10_state_线程六种状态 {

    public static void main(String[] args) throws InterruptedException {
        /**
         * 线程1 没有start()                      -------  NEW
         */
        Thread t1 = new Thread(() -> {

            log.debug("running......");

        }, "t1");

        /**
         * 线程2 死循环一直运行                    -------  RUNNABLE
         */
        Thread t2 = new Thread(()->{

            while(true){ // Java里的运行：RUNNABLE [有可能分到时间片]，[也有可能分不到] ，[也有可能陷入到操作系统的IO阻塞]

            }

        },"t2");

        t2.start();

        /**
         * 线程3  主线程睡眠500ms 后， t3.getState() ------ TERMINATED
         */
        Thread t3 = new Thread(() -> {

            log.debug("running......");

        }, "t3");
        t3.start();


        /**
         * 线程4  有时间的等待                      ------ TIMED_WAITING
         */
        Thread t4 = new Thread(() -> {

            synchronized (T10_state_线程六种状态.class){

                try {
                    Thread.sleep(1000000);  // 对应 Java六种状态的  [TIMED_WAITING 有时限的等待]
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }, "t4");
        t4.start();


        /**
         * 线程5  join来等待t2(死循环不会停)运行结束   [WAITING 无时限的等待]
         */
        Thread t5 = new Thread(()->{

            try {
                t2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        },"t5");

        t5.start();

        /**
         * 线程6  t4已经上锁了，等待t4释放锁 才能运行   [BLOCKED 阻塞状态]
         */
        Thread t6 = new Thread(()->{

            synchronized (T10_state_线程六种状态.class){

                try {
                    Thread.sleep(1000000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        },"t6");

        t6.start();


        // 主线程休眠
        Thread.sleep(500);

        log.debug("t1 state : {} ", t1.getState());
        log.debug("t2 state : {} ", t2.getState());
        log.debug("t3 state : {} ", t3.getState());
        log.debug("t4 state : {} ", t4.getState());
        log.debug("t5 state : {} ", t5.getState());
        log.debug("t6 state : {} ", t6.getState());
    }


}
